import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/modules/CustomRoute.dart';
import 'package:mfkb/pages/web/WebViewByUrl.dart';
import 'package:mfkb/pages/web/WebViewPlugin.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/FunService.dart';
import 'package:toast/toast.dart';

class NewsList extends StatefulWidget {
  @override
  _NewsListState createState() => _NewsListState();
}

class _NewsListState extends State<NewsList> {

  int page = 1 ;
  dynamic list ;
  ScrollController _controller = ScrollController() ;
  bool canFlush = true ;
  bool loading = false ;

  @override
  void initState() {
    super.initState();
    _controller.addListener((){
      //判断是否滑动到了页面的最底部
      if(_controller.position.pixels == _controller.position.maxScrollExtent){
        //如果不是最后一页数据，则生成新的数据添加到list里面
        if(canFlush && !loading){
          _retrieveData();
        }
      }
    }) ;
    initData() ;
  }

  initData(){
    page = 1 ;
    loading = true ;
    FunService().news(page).then((value){
      if(value["code"] == 200){
        list = value["data"]["list"] ;
      }else {
        Toast.show(value["msg"], context) ;
      }
      setState(() {
        loading = false ;
      });
    }) ;
  }

  _retrieveData(){
    loading = true ;
    FunService().news(page+1).then((value){
      if(value["code"] == 200){
        page = page + 1 ;
        int length = value["data"]["list"].length ; 
        if(length == 0){
          canFlush = false ;
        }
        for(var i = 0 ; i < length ; i++){
          list.add(value["data"]["list"][i]) ;
        }
      }else {
        Toast.show(value["msg"], context) ;
      }
      setState(() {
        loading = false ;
      });
    }) ;
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child: Scaffold(
        body: Container(
          color:Color.fromARGB(255, 245, 246, 248) ,
          child: Column(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).padding.top ,
              ) ,
              Container(
                height: 45,
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 17,
                      height: 17,
                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(19)),
                      child: GestureDetector(
                        child: Container(
                          width: 17,
                          height: 17,
                          child: Image.asset("assets/images/back.png" , fit: BoxFit.fill,),
                        ),
                        onTap: (){
                          Navigator.of(context).pop() ;
                        },
                      ),
                    ) ,
                    Expanded(
                      child: Container(
                        child: Center(
                          child: Text("校园资讯" , style: TextStyle( 
                            color: Color.fromARGB(255, 19 , 28 , 53) , 
                            fontSize: ScreenUtil().setSp(18) , 
                            fontWeight: FontWeight.bold  
                          ),), 
                        ),
                      ),
                    ) ,
                    Container(
                      height: 17 ,
                      width: 36 ,
                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)) ,
                    ) 
                  ],
                ),
              ) ,
              Expanded(
                child: ScrollConfiguration(
                  behavior: MyBehavior() ,
                  child: ListView(
                    controller: _controller ,
                    padding: EdgeInsets.all(0),
                    children: List.generate(list == null ? 0 : list.length, (index){
                      return GestureDetector(
                        child: Container(
                          margin: EdgeInsets.only(top:ScreenUtil().setHeight(8) , left:ScreenUtil().setWidth(10) , right:ScreenUtil().setWidth(10) , bottom:ScreenUtil().setHeight(index == list.length-1 ? 8 : 0)),
                          height: ScreenUtil().setHeight(128),
                          decoration: BoxDecoration(
                            color: Colors.white ,
                            borderRadius: BorderRadius.all(Radius.circular(8))
                          ),
                          child: Column(
                            children: <Widget>[
                              Container(
                                height: ScreenUtil().setHeight(42),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Container(
                                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(12)),
                                        child: Text(formatDate(DateTime.fromMillisecondsSinceEpoch(list[index]["time"]), [yyyy, '-', mm, '-', dd]) , style: TextStyle(
                                          fontSize: ScreenUtil().setSp(14) ,
                                          fontWeight: FontWeight.bold ,
                                          color: Color.fromARGB(255, 19, 28, 53)
                                        ),),
                                      ),
                                    ) ,
                                    Container(
                                      width: ScreenUtil().setWidth(80),
                                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(11)),
                                      child: Text("点击查看" , textAlign: TextAlign.end,style: TextStyle(
                                        fontSize: ScreenUtil().setSp(12) ,
                                        color: Color.fromARGB(255, 78, 86, 109)
                                      ),),
                                    )
                                  ],
                                ),
                              ) ,
                              Container(
                                height: 1,
                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(11) , right:ScreenUtil().setWidth(8)),
                                color: Color.fromARGB(255, 238, 238, 238),
                              ) ,
                              Expanded(
                                child: Container(
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Container(
                                        height: ScreenUtil().setHeight(57),
                                        width: ScreenUtil().setHeight(80),
                                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(12) , top:ScreenUtil().setHeight(16)),
                                        child: CachedNetworkImage(
                                          placeholder: (ct , url){
                                            return Container(
                                              color: Color.fromARGB(255, 246, 245, 248),
                                              child: Center(
                                                child: Image.asset("assets/images/imageloading.png"),
                                              ),
                                            ) ;
                                          },
                                          fit: BoxFit.fill ,
                                          imageUrl: Config().getImgHost() + list[index]["cover"] ,
                                        ),
                                      ) ,
                                      Expanded(
                                        child: Container(
                                          margin: EdgeInsets.only(right:ScreenUtil().setWidth(11) , top:ScreenUtil().setHeight(19) , left: ScreenUtil().setWidth(17)),
                                          child: Text(list[index]["title"] , maxLines: 2, style: TextStyle(
                                            fontSize: ScreenUtil().setSp(15) ,
                                            color: Color.fromARGB(255, 19, 27, 54)
                                          ),overflow: TextOverflow.ellipsis,),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        onTap: (){
                          //Navigator.of(context).push(CustomRoute(WebViewPlugin(file: list[index]["file"] , md5:list[index]["file_md5"] , type:1))) ;   
                          if(list[index]["type"] == 1){
                            Navigator.of(context).push(CustomRoute(WebViewPlugin(file: list[index]["file"], md5: list[index]["file_md5"] , type: 1,))) ;
                          }else if(list[index]["type"] == 2){
                            Navigator.of(context).push(CustomRoute(WebViewByUrl(url: list[index]["file"]))) ;
                          }
                        },
                      ) ;
                    }),
                  ),
                ),
              )
            ]
          )
        )
      ),
    );
  }
}